const db = require("../db/index")
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const config = require("../config")
// 注册新用户
exports.regUser = (req, res) => {
    const userinfo = req.body;
    const sql = "select * from ev_user where username = ?";
    db.query(sql, [userinfo.username], (err, result) => {
        if (err) {
            return res.cc(err);
        }
        if (result.length > 0) {
            return res.cc("用户名已存在！");
        }
        // console.log(userinfo);
        // 对密码进行加密
        userinfo.password = bcrypt.hashSync(userinfo.password, 10);
        // console.log(userinfo);
        // 插入新用户
        const sql2 = "insert into ev_user set ?";
        db.query(sql2, userinfo, (err, result) => {
            if (err) {
                return res.cc(err);
            }
            if (result.affectedRows !== 1) {
                return res.cc("注册用户失败！");
            }
            res.send({
                status: 200,
                message: "注册成功！"
            })
        })
            
    })
}
// 登录
exports.login = (req, res) => {
    const userinfo = req.body;
    const sql = "select * from ev_user where username = ?";
    db.query(sql,[userinfo.username],function(err,result){
        if(err)
            return res.cc(err);
        if(result.length !==1)
            return res.cc("用户名不存在！")
        const compareResult = bcrypt.compareSync(userinfo.password,result[0].password);
        if(!compareResult)
            return res.cc("密码错误！")
        const user = {
            ...result[0],password:'',user_pic:""
        }
        
        const token= jwt.sign(user,config.jwtSecretKey,{expiresIn:"10h"})
        // console.log("token:",token)
        res.send({
            status:200,
            message:"账号登陆成功！",
            data:{
                token:"Bearer "+token
            }
        })

    })
    
}
